﻿#include "htshandler.h"

bool HTSHandler::load(const QString &fileName)
{
    _file=fileName;
    QFile file(_file);

    if(file.exists() && file.open(QFile::ReadOnly | QFile::Text))
    {
        QJsonDocument doc;

        QFileInfo fi(_file);
        if(fi.suffix() == "json")
            doc=QJsonDocument::fromJson(file.readAll());
        else
            doc=QJsonDocument::fromBinaryData(file.readAll());

        if(!doc.isEmpty() && doc.isObject())
        {
            QJsonObject obj=doc.object();
            _title=obj.value("title").toString();
            _jsonArray=obj.value("content").toArray();
            for(int i=0;i<_jsonArray.size();i++)
            {
                QJsonObject obj=_jsonArray[i].toObject();
                _head=obj.value(HT_HEAD).toString();
                _tail=obj.value(HT_TAIL).toString();

                _headList.append(_head);
                _hashTable.insert(_head,_tail);
            }
            return true;
        }
        else
            return false;
    }
    else
        return false;
}

bool HTSHandler::save(const QString &fileName)
{
    QFile file(fileName);
    if(file.open(QFile::WriteOnly | QFile::Text))
    {
        QJsonObject obj;
        obj.insert("title",_title);
        obj.insert("content",_jsonArray);

        QJsonDocument doc(obj);
        QFileInfo fi(fileName);
        if(fi.suffix() == "json")
            file.write(doc.toJson());
        else
            file.write(doc.toBinaryData());
        file.close();
        return true;
    }
    else
        return false;
}

QString HTSHandler::getFileName() const
{
    return _file;
}

void HTSHandler::setFileName(const QString &fileName)
{
    _file=fileName;
}

QString HTSHandler::getTitle() const
{
    return _title;
}

void HTSHandler::setTitle(const QString &title)
{
    _title=title;
}

QStringList HTSHandler::getHeadList() const
{
    return _headList;
}

QHash<QString,QString> HTSHandler::getHashTable() const
{
    return _hashTable;
}

QJsonArray HTSHandler::getJsonArray() const
{
    return _jsonArray;
}

void HTSHandler::setJsonArray(const QJsonArray &array)
{
    _jsonArray=array;
}

void HTSHandler::append(const QString &head, const QString &tail)
{
    QJsonObject obj;
    obj.insert(HT_HEAD,head);
    obj.insert(HT_TAIL,tail);
    _jsonArray.append(obj);
}

void HTSHandler::remove(int pos)
{
    _jsonArray.removeAt(pos);
}
